//var validation = new Validation('signup-form', {immediate : true, onSubmit : false});
function log(result, error) {
  if (!error) {
    $("container").update(JSON.stringify(result) + "\n");
  } else {
    $("container").update("ERROR <pre>" + JSON.stringify(result).replace(/(\\n)+/g, "<br/>") + "</pre>\n");
  }
}

//Event.observe($('signup-form'), 'submit', validate_and_post, false);
function formCallback(result, form) {
  window.status = "valiation callback for form '" + form.id + "': result = " + result;
}
Validation.addAllThese([
    ['validate-password', 'Your password must be more than 6 characters and not be \'password\' or the same as your name', {
      minLength : 7,
      notOneOf : ['password','PASSWORD','1234567','0123456'],
      notEqualToField : 'email'
    }],
    ['validate-password-confirm', 'Your confirmation password does not match your first password, please try again.', {
      equalToField : 'password'
    }],
    ['validate-username', 'Your username must be at least 6 characters long and must be alphanumeric.', {
      minLength : 7,
      pattern : /^[a-zA-Z\d]+$/
    }],

    ]);
Event.onReady(function() {
  console.log('window loaded' + new Date());
  var valid = new Validation('signup-form', {immediate : true, onSubmit : false});
  Field.focus($("email"));
  Event.observe('signup-form', 'submit', function(e) {
    Event.stop(e);
    validate_and_post(valid);
  });
  //$('signup-form').onsubmit = function() {return false;};
});

function erlang_create_accont(args) {  
  var testService = new JsonRpcTransaction("/json_rpc/account", "signup", [args.serialize({hash: true,submit: 'delete' })]);
  testService.addCallback(log);
  testService.addErrorCallback(log);
}

function validate_and_post(valid) {
  //$('submit_button').disable();
  var vrs = valid.validate();
  valid.decorateAll(vrs);
  //console.log(Object.toJSON(vrs));
  if (vrs.pluck('results').flatten().pluck('passes').all()) {
    //submit_form($('signup-form'))
    var server_response = erlang_create_accont($('signup-form'));
    var validation_from_erlang = [{'elmId': 'textMEName', 'value': 'Edward_Acki', 'results': [{'className': 'validate-username-server', 'passes': false, 'message': 'Edwar_Acki username is already been taken. Try another one'}]}];
    validation_from_erlang = server_response;
    if (validation_from_erlang.pluck('results').flatten().pluck('passes').all()) {
      console.log('GIT !!!');
      return true;
    } else {
      valid.decorateAll(validation_from_erlang);
      return false;
    }
  } else {
    return false;
  }
}

